package com.vinfai.thread.concurrent.locks;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * java5 显式锁LOCK
 * @author vinfai
 *
 */
public class InterruptedLock extends Thread{
	public static Lock lock = new ReentrantLock();
	
	@Override
	public void run(){
		try {
			//申请锁过程中，如果当前线程被中断，则抛出InterruptedException异常.
			lock.lockInterruptibly();//wait acquired lock. can be interrupted ...
		} catch (InterruptedException e) {
			System.out.println("current thread is interrupted...");
			e.printStackTrace();
		}
		
		//如果运行到这里, 说明已经申请到锁, 且没有发生异常
		try{
			System.out.println(" Interruptedlock thread is running....");
		}finally{
			System.out.println(" InterruptedLock 释放锁!");
			lock.unlock();
		}
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) throws InterruptedException{
		//ConcurrentHashMap<K, V>
		//
		//AbstractQueuedSynchronizer
		//ReentrantReadWriteLock.ReadLock;
		
		BlockingQueue<String> queue = new ArrayBlockingQueue<String>(10);
		
		//Lock _lock = InterruptedLock.lock;
		//_lock.lock();//获得锁,被主线程获得。lockThread则需要等待了。
		lock.lock();
		try {
			Thread lockThread = new InterruptedLock();
			lockThread.start();//启动线程，等待获得锁.
			
			Thread.sleep(5000);
			System.out.println("主线程调用 InterruptedLock.Interrupt()");
			lockThread.interrupt();
		} finally{
			System.out.println("主线程 unlock method...");
//			_lock.unlock();
			lock.unlock();
		}
		
	}
}
